package utils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.Environment;
import android.text.Layout;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.text.TextUtils;

import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.ref.WeakReference;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.TimeUnit;

import log.LogManager;
import utils.common.ScreenTools;
import utils.common.StringUtils;
import utils.common.TimeUtils;
import utils.common.ToastUtil;

public class FileUtil {
    public static String mSdCardRoot;

    public static String MAR_DIR = Environment.getExternalStorageDirectory() + "/mar/";

    public static String MAR_DIR_IMAGE = Environment.getExternalStorageDirectory() + "/mar/image/";

    public static String MAR_DIR_VOICE = Environment.getExternalStorageDirectory() + "/mar/voice/";

    public static String MAR_DIR_VIDEO = Environment.getExternalStorageDirectory() + "/mar/video/";

    public static String VOICE_DIR = Environment.getExternalStorageDirectory() + "/mdlk_im/voice/";

    public static String MAR_DIR_DOWNLOAD = Environment.getExternalStorageDirectory() + "/mar/download/";

    static {
        mSdCardRoot = Environment.getExternalStorageDirectory().getAbsolutePath() + "/";

        //创建mar 文件夹
        makeFileDir(MAR_DIR, true);
        makeFileDir(MAR_DIR_IMAGE, true);
        makeFileDir(MAR_DIR_VOICE, true);
        makeFileDir(MAR_DIR_VIDEO, true);
        makeFileDir(MAR_DIR_DOWNLOAD, true);
    }

    public static String getImageTmpPath(String filename) {
        String path = PhotoUtil.getTmpPath() + "/";
        File dirFile = new File(path);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
        return path + filename;
    }

   /* public static String getImageTmpPath() {
        return FileUtil.getImageTmpPath(BaseApplication.UPLOAD_PHOTO_NAME);
    }*/

    /**
     * 解决小米部分系统无法返回data的bug
     *
     * @return 相机或相册裁剪返回的临时Uri
     */
    public static Uri getImageTmpUri() {
        return Uri.fromFile(PhotoUtil.getCopFilePath());
    }

    /**
     * 获取当前毫秒数
     *
     * @return
     */
    public static String getCurMillions() {
        return System.currentTimeMillis() + "";
    }

    /**
     * 获取当前毫秒数
     *
     * @return
     */
    public static long getCurrentTimeMillis() {
        return System.currentTimeMillis();
    }

    /**
     * 将字符串毫秒转为long
     *
     * @return
     */
    public static long stringMillionsToLong(String mil) {
        long m = 0;
        try {
            m = Long.parseLong(mil);
        } catch (Exception e) {
            m = new Date().getTime();
        }
        return m;
    }

    /**
     * 将long 时间转换为 上午 12:05的格式
     *
     * @return
     */
    public static String stringMillionsToParseTime(long mil) {
        DateFormat dateFormat = new SimpleDateFormat("a h:mm");
        String time = dateFormat.format(mil);

        String index = time.substring(0, 2);
        if (index.toLowerCase().startsWith("am")) {
            time = time.replace(index, "上午");
        } else if (index.toLowerCase().startsWith("pm")) {
            time = time.replace(index, "下午");
        }
        return time;
    }

    /**
     * 将long 时间转换为 24：00 的格式
     *
     * @return
     */
    public static String stringMillionsToAHour(long mil) {
        return TimeUtils.getTimeHourMinute(mil);
    }

    public static long getDateTime(String d) {
        long m = 0;
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = sdf.parse(d);
            m = date.getTime();// Long类型变量
        } catch (Exception e) {
            e.printStackTrace();
            m = new Date().getTime();
        }
        return m;
    }

    /**
     * 将当前的毫秒转为时间
     *
     * @param mil
     * @return
     */
    public static String getDataTimeFromMillions(String mil) {
        if (mil == null)
            return "";
        long m = 0;
        if (mil != null && mil.contains(":")) {//Date 转 毫秒
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
                Date date = sdf.parse(mil);
                m = date.getTime();//Long类型变量
            } catch (Exception e) {
                e.printStackTrace();
                m = new Date().getTime();
            }
        } else {
            m = stringMillionsToLong(mil);
        }
        return getDataTimeFromMillions(m);
    }

    public static String getDataTimeCircleMillions(String mil) {
        if (StringUtils.isEmpty(mil))
            return "";

        return getDataTimeCircleMillions(Long.valueOf(mil));
    }

    public static String getDataTimeCircleMillions(long mil) {
        String time = "";
        Date date = new Date(mil);//发过来的时间
        Date now = new Date(getCurrentTimeMillis());
        long l = now.getTime() - date.getTime();
        long day = l / (24 * 60 * 60 * 1000);
        long hour = (l / (60 * 60 * 1000) - day * 24);
        long min = ((l / (60 * 1000)) - day * 24 * 60 - hour * 60);
        long s = (l / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);
        //System.out.println("HTTP = "+day+"天"+hour+"小时"+min+"分"+s+"秒");
        if (day <= 0) {//当天消息
            if (hour > 1) {
                time = hour + "小时前";
            } else {
                if (min <= 0) {
                    //time = s + "秒前";
                    time = "刚刚";
                } else {
                    time = min + "分钟前";
                }
            }
        } else {//不是当天
            if (day == 1) {//昨天的消息
                time = "昨天";
            } else if (day == 2) {//前天的消息
                time = "前天";
            } else {//其他天
                time = day + "天前";
            }
        }
        return time;
    }


    /**
     * 将当前的毫秒转为时间
     *
     * @param mil
     * @return
     */
    public static String getDataTimeFromMillions(long mil) {
        SimpleDateFormat dateFormat = null;
        String time = "";

        Date sendDate = new Date(mil);//发过来的时间
        Date curDate = new Date(getCurrentTimeMillis());

        if (sendDate.getYear() == curDate.getYear()) {//同一年的消息
            int sendDay = sendDate.getDate();
            int curDay = curDate.getDate();

            if (sendDay == curDay) {//当天消息
                time = stringMillionsToAHour(mil);
            } else {//不是当天
                if (curDay - sendDay == 1) {//昨天的消息
                    time = "昨天 " + stringMillionsToAHour(mil);
                } else if (curDay - sendDay == 2) {//前天的消息
                    time = "前天 " + stringMillionsToAHour(mil);
                } else {//其他天
                    dateFormat = new SimpleDateFormat("MM月dd日");
                    time = dateFormat.format(mil);
                }
            }
        } else {
            dateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm");
            time = dateFormat.format(mil);
        }
        return time;
    }


    /**
     * 计算两个时间的间隔天数
     *
     * @param time1
     * @param time2
     * @return
     * @throws ParseException
     */
    public static int getIntervalDayNum(long time1, long time2) {
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        int betweenDays = 0;

        Date d1 = new Date(time1);
        Date d2 = new Date(time2);
        Calendar c1 = Calendar.getInstance();
        Calendar c2 = Calendar.getInstance();
        c1.setTime(d1);
        c2.setTime(d2);
        // 保证第二个时间一定大于第一个时间
        if (c1.after(c2)) {
            c1 = c2;
            c2.setTime(d1);
        }
        int betweenYears = c2.get(Calendar.YEAR) - c1.get(Calendar.YEAR);
        betweenDays = c2.get(Calendar.DAY_OF_YEAR)
                - c1.get(Calendar.DAY_OF_YEAR);
        for (int i = 0; i < betweenYears; i++) {
            c1.set(Calendar.YEAR, (c1.get(Calendar.YEAR) + 1));
            betweenDays += c1.getMaximum(Calendar.DAY_OF_YEAR);
        }
        return betweenDays;
    }

    /**
     * 获取随机数
     *
     * @return
     */
    public static int getRandomNumber() {
        return (int) (Math.random() * 1000);
    }

    /**
     * 获取 im msgid
     */
    public static String getMessageId() {
        return SharedPreUtil.getInstance().getValue(SharedPreUtil.UUID) + getCurrentTimeMillis() + getRandomNumber();
    }

    /**
     * 获取文件后缀名
     *
     * @param path
     * @return
     */
    public static String getSuffixName(String path) {
        int t = path.lastIndexOf(".");
        return path.substring(t + 1);
    }

    /**
     * 删除文件夹的所有文件
     *
     * @param destDir
     */
    public static void deleteDir(String destDir) {
        File dir = new File(destDir);

        if (dir.exists() && dir.isDirectory()) {
            String[] children = dir.list();
            for (int i = 0; i < children.length; i++) {
                File subDir = new File(dir, children[i]);
                deleteFile(subDir.getAbsolutePath());
            }
        }
    }

    /**
     * 创建新的文件
     *
     * @param destFileName
     * @return
     */
    public static File createFile(String destFileName) {
        File file = new File(destFileName);

        if (destFileName.endsWith(File.separator)) {
            System.out.println("创建单个文件" + destFileName + "失败，目标文件不能为目录！");
        }
        //判断目标文件所在的目录是否存在
        if (!file.getParentFile().exists()) {
            //如果目标文件所在的目录不存在，则创建父目录
            System.out.println("目标文件所在目录不存在，准备创建它！");
            if (!file.getParentFile().mkdirs()) {
                System.out.println("创建目标文件所在目录失败！");
            }
        }
        //删除原来的文件
        if (file.exists()) {
            deleteFile(destFileName);
        }
        //创建目标文件
        try {
            if (file.createNewFile()) {
                System.out.println("创建单个文件" + destFileName + "成功！");
                return file;
            } else {
                System.out.println("创建单个文件" + destFileName + "失败！");
                return null;
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("创建单个文件" + destFileName + "失败！" + e.getMessage());
            return null;
        }
    }

    /**
     * 新建文件夹
     *
     * @param path
     * @param b
     */
    public static void makeFileDir(String path, boolean b) {
        String d = path;
        if (!b) {
            d = Environment.getExternalStorageDirectory().toString() + path;
        }
        File dir = new File(d);
        if (!dir.exists()) {
            dir.mkdirs();
        }
    }

    /**
     * Bitmap 转字节数组
     *
     * @param bm
     * @return
     */
    public static byte[] Bitmap2Bytes(Bitmap bm) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
        return baos.toByteArray();
    }

    /**
     * 节数组 转Bitmap
     *
     * @param bytes
     * @return
     */
    public static Bitmap Bytes2Bitmap(byte[] bytes) {
        ByteArrayInputStream isBm = null;
        isBm = new ByteArrayInputStream(bytes);
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);
        isBm.reset();
        closeQuietly(isBm);
        return bitmap;
    }

    /**
     * 图片按质量压缩
     *
     * @param image
     * @return
     */
    public static Bitmap compressImage(Bitmap image) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        int options = 100;
        while (baos.toByteArray().length / 1024 > 100) { // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
            baos.reset();// 重置baos即清空baos
            options -= 10;// 每次都减少10
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%，把压缩后的数据存放到baos中

        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream数据生成图片
        return bitmap;
    }

    /**
     * convertToBitmap根据地址　获取bitmap
     *
     * @return Object 返回对象描述
     * @Exception 异常描述
     */
    public static Bitmap convertToBitmap(String path, int w, int h) {
        BitmapFactory.Options opts = new BitmapFactory.Options();
        // 设置为ture只获取图片大小
        opts.inJustDecodeBounds = true;
        opts.inPreferredConfig = Bitmap.Config.ARGB_8888;
        // 返回为空
        BitmapFactory.decodeFile(path, opts);
        int width = opts.outWidth;
        int height = opts.outHeight;
        float scaleWidth = 0.f, scaleHeight = 0.f;
        if (width > w || height > h) {
            // 缩放
            scaleWidth = ((float) width) / w;
            scaleHeight = ((float) height) / h;
        }
        opts.inJustDecodeBounds = false;
        float scale = Math.max(scaleWidth, scaleHeight);
        opts.inSampleSize = (int) scale;
        WeakReference<Bitmap> weak = new WeakReference<Bitmap>(BitmapFactory.decodeFile(path, opts));
        return Bitmap.createScaledBitmap(weak.get(), w, h, true);
    }

    /**
     * 图片根据Bitmap 按比例压缩 再按质量压缩
     *
     * @param bitmap
     * @return
     */
    public static Bitmap compressionBitmapFromBitmap(Bitmap bitmap) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 40, baos);
        return Bytes2Bitmap(baos.toByteArray());
    }


    /**
     * 根据480*800尺寸压缩，再对质量压40%
     *
     * @param filePath   目标地址
     * @param targetPath 临时地址
     * @return
     */
    public static String bitmapToString(String filePath, String targetPath) {
        Bitmap bm = getSmallBitmap(filePath, 480, 800);
        if (bm == null)
            return filePath;
        FileOutputStream fileOutputStream;
        try {
            fileOutputStream = new FileOutputStream(new File(targetPath));
            bm.compress(Bitmap.CompressFormat.JPEG, 80, fileOutputStream);
            fileOutputStream.flush();
            fileOutputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            bm.recycle();
            bm = null;
        }
        return targetPath;
    }


    /**
     * 根据屏幕尺寸压缩，再对质量压40%
     *
     * @param context
     * @param filePath
     * @return
     */
    public static String bitmapToString(Context context, String filePath) {
        String suffix = getFileExtension(filePath);
        if (!TextUtils.isEmpty(suffix) && "gif".equals(suffix.toLowerCase())){
            return filePath;
        }else {
            int degree = BitmapHelper.getDegress(filePath);
            Bitmap bm = getSmallBitmap(filePath, 480, 800);
            if (degree > 0) {
                bm = BitmapHelper.rotateBitmap(bm, degree);
            }
            if (bm == null)
                return filePath;
            FileOutputStream fileOutputStream;
            String index = AESEncryptUtils.md5String(TimeUtils.getCurrentTimeLong() + (int) (Math.random() * 1000));
            String newPath = PhotoUtil.getCacheImage(index);
            try {
                fileOutputStream = new FileOutputStream(new File(newPath));
                bm.compress(Bitmap.CompressFormat.JPEG, 80, fileOutputStream);
                fileOutputStream.flush();
                fileOutputStream.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                bm.recycle();
                bm = null;
            }
            return newPath;
        }
    }

    /**
     * 根据480*800尺寸压缩，再对质量压40%
     *
     * @param filePath
     * @return
     */
    public static String bitmapToString(String filePath) {
        String suffix = getFileExtension(filePath);
        if (!TextUtils.isEmpty(suffix) && "gif".equalsIgnoreCase(suffix)) {
            return filePath;
        } else {
            int degree = BitmapHelper.getDegress(filePath);
            Bitmap bm = getSmallBitmap(filePath, 480, 800);
            if (degree > 0) {
                bm = BitmapHelper.rotateBitmap(bm, degree);
            }
            if (bm == null)
                return filePath;
            FileOutputStream fileOutputStream;
            String newPath = PhotoUtil.getCacheImage(PhotoUtil.uuid());
            try {
                fileOutputStream = new FileOutputStream(new File(newPath));
                bm.compress(Bitmap.CompressFormat.JPEG, 80, fileOutputStream);
                fileOutputStream.flush();
                fileOutputStream.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                bm.recycle();
                bm = null;
            }
            return newPath;
        }
    }

    /**
     * 存储本地图片
     *
     * @return
     */
    public static String bitmapToStringCertificat(Bitmap bitmap, String name) {
        if (bitmap == null)
            return null;
        FileOutputStream fileOutputStream;
        String newPath = PhotoUtil.getCacheImage(name);
        try {
            fileOutputStream = new FileOutputStream(new File(newPath));
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
            fileOutputStream.flush();
            fileOutputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //bitmap.recycle();
        }
        return newPath;
    }

    /**
     * 存储本地图片（分享logo）
     *
     * @return
     */
    public static String bitmapToStringShare(Bitmap bitmap) {
        if (bitmap == null)
            return null;
        FileOutputStream fileOutputStream;
        String newPath = PhotoUtil.getCacheImage("share");
        try {
            fileOutputStream = new FileOutputStream(new File(newPath));
            bitmap.compress(Bitmap.CompressFormat.JPEG, 80, fileOutputStream);
            fileOutputStream.flush();
            fileOutputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            bitmap.recycle();
        }
        return newPath;
    }

    /**
     * 存储本地图片（分享logo）
     *
     * @return
     */
    public static String bitmapToStringShare(Context context, Bitmap bitmap, String fileName) {
        if (bitmap == null)
            return null;
        FileOutputStream fileOutputStream;
        String newPath = PhotoUtil.saveImage(fileName);
        File file = new File(newPath);
        try {
            fileOutputStream = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
            fileOutputStream.flush();
            fileOutputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            bitmap.recycle();
        }


        // 其次把文件插入到系统图库
        /*try {
            MediaStore.Images.Media.insertImage(context.getContentResolver(),
                    file.getAbsolutePath(), fileName, null);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }*/
        // 最后通知图库更新
        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        Uri uri = Uri.fromFile(file);
        intent.setData(uri);
        context.sendBroadcast(intent);
        ToastUtil.showSuccessMsg(context, "保存成功" + "\r\n" + file.getAbsolutePath());
        return newPath;
    }

    /**
     * 压缩图片不超过30K
     *
     * @param image
     * @return
     */
    public static Bitmap compBitmap(Bitmap image) {
        if (image == null)
            return null;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 20, baos);
        int as = baos.toByteArray().length;
        int quality = 100;
        while (baos.toByteArray().length > 20 * 1024) {
            baos.reset();
            image.compress(Bitmap.CompressFormat.JPEG, quality, baos);
            quality -= 20;
        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);
        return bitmap;
    }

    /**
     * 压缩图片不超过30K
     *
     * @param image
     * @return
     */
    public static byte[] compByte(Bitmap image) {
        if (image == null)
            return null;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 20, baos);
        int as = baos.toByteArray().length;
        int quality = 100;
        while (baos.toByteArray().length > 20 * 1024) {
            baos.reset();
            image.compress(Bitmap.CompressFormat.JPEG, quality, baos);
            quality -= 20;
        }
        return baos.toByteArray();
    }

    /**
     * 把filePath转换成byte[]
     *
     * @param filePath
     * @return
     */
    public static byte[] bitmapTobyte(String filePath) {
        Bitmap bm = getSmallBitmap(filePath, 480, 800);
        ByteArrayOutputStream byteArrayOutputStream = null;
        if (bm == null)
            return new byte[0];
        byteArrayOutputStream = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
        byte[] bytes = byteArrayOutputStream.toByteArray();
        byteArrayOutputStream.reset();
        closeQuietly(byteArrayOutputStream);
        bm.recycle();
        return bytes;
    }

    public static byte[] bitmapTobytes(Context context, String filePath) {
        Bitmap bm = getSmallBitmap(filePath, ScreenTools.getInstance(context).getScreenWidth(),
                ScreenTools.getInstance(context).getScreenHeight());
        ByteArrayOutputStream byteArrayOutputStream = null;
        if (bm == null)
            return new byte[0];
        byteArrayOutputStream = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.JPEG, 40, byteArrayOutputStream);
        byte[] bytes = byteArrayOutputStream.toByteArray();
        byteArrayOutputStream.reset();
        closeQuietly(byteArrayOutputStream);
        bm.recycle();
        return bytes;
    }

    public static String bitmapToStringCom(String filePath, String targetPath) {
        Bitmap bm = getSmallBitmap(filePath, 480, 800);
        if (bm == null)
            return filePath;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        byte[] b = baos.toByteArray();
        double mid = b.length / 1024;
        //图片允许最大空间 单位：KB
        double maxSize = 150.00;
        if (mid > maxSize) {
            baos.reset();
            double option = (maxSize / mid) * 100;
            bm.compress(Bitmap.CompressFormat.PNG, (int) option, baos);
        }
        byte[] b1 = baos.toByteArray();
        double mid1 = b1.length / 1024;
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(new File(targetPath));
            fileOutputStream.write(baos.toByteArray());
            fileOutputStream.flush();
            fileOutputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            bm.recycle();
            try {
                baos.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            bm = null;
            System.gc();
        }
        return targetPath;
    }


    public static String bitmapToString(Bitmap bm, String targetPath) {

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.JPEG, 40, byteArrayOutputStream);
        FileOutputStream fileOutputStream;
        try {
            fileOutputStream = new FileOutputStream(new File(targetPath));
            fileOutputStream.write(byteArrayOutputStream.toByteArray());
            fileOutputStream.flush();
            fileOutputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //bm.recycle();
            bm = null;
        }
        return targetPath;

    }


    /**
     * 基于质量的压缩算法， 此方法未 解决压缩后图像失真问题
     * <br> 可先调用比例压缩适当压缩图片后，再调用此方法可解决上述问题
     *
     * @param bitmap
     * @param maxBytes 压缩后的图像最大大小 单位为byte
     * @return
     */
    public final static Bitmap compressBitmap(Bitmap bitmap, long maxBytes) {
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
            int options = 90;
            while (baos.toByteArray().length > maxBytes) {
                baos.reset();
                bitmap.compress(Bitmap.CompressFormat.PNG, options, baos);
                options -= 10;
            }
            byte[] bts = baos.toByteArray();
            Bitmap bmp = BitmapFactory.decodeByteArray(bts, 0, bts.length);
            baos.close();
            return bmp;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }


    /**
     * 图片加水印 也可以加文字
     */
    public static Bitmap watermarkBitmap(String path, Bitmap watermark,
                                         String title) {
        Bitmap bitmap = BitmapFactory.decodeFile(path);
        return watermarkBitmap(bitmap, watermark, title);
    }

    public static Bitmap watermarkBitmap(Bitmap src, Bitmap watermark,
                                         String title) {
        if (src == null) {
            return null;
        }
        int w = src.getWidth();
        int h = src.getHeight();
        Bitmap newb = Bitmap.createBitmap(w, h, Bitmap.Config.RGB_565);
        Canvas cv = new Canvas(newb);
        cv.drawBitmap(src, 0, 0, null);
        //加入图片
        if (watermark != null) {
            int ww = watermark.getWidth();
            int wh = watermark.getHeight();
            cv.drawBitmap(watermark, 10, h / 2 - wh / 2, null);
        }
        //加入文字
        if (title != null) {
            int minSize = w < h ? w : h;
            String familyName = "宋体";
            Typeface font = Typeface.create(familyName, Typeface.BOLD);
            TextPaint textPaint = new TextPaint();
            textPaint.setColor(Color.RED);
            textPaint.setAlpha(50);
            textPaint.setTypeface(font);
            textPaint.setTextSize(minSize / 20);
            //这里是自动换行的，width控制一行绘制多宽
            StaticLayout layout = new StaticLayout(title, textPaint, w - w / 5, Layout.Alignment.ALIGN_NORMAL, 1.0F, 0.0F, true);
            //Paint.FontMetrics fontMetrics = textPaint.getFontMetrics();
            cv.translate(w / 10, h / 2 - layout.getHeight() / 2);//开始绘制的位置
            layout.draw(cv);
        }
        cv.save(Canvas.ALL_SAVE_FLAG);
        cv.restore();
        return newb;
    }

    /**
     * 根据路径获得突破并压缩返回bitmap用于显示
     *
     * @param filePath
     * @return
     */
    public static Bitmap getSmallBitmap(String filePath, int reWidth, int reHeight) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        options.inPreferredConfig = Bitmap.Config.RGB_565;
        BitmapFactory.decodeFile(filePath, options);
        options.inSampleSize = calculateInSampleSize(options, reWidth, reHeight);
        options.inJustDecodeBounds = false;
        LogManager.getLogger().d("getSmallBitmap", "filePath==>" + filePath);
        return BitmapFactory.decodeFile(filePath, options);
    }

    /**
     * 大图片  背景图 引导图...
     *
     * @param context
     * @param resId
     * @return
     */
    public static Drawable LargeImage2Drawable(Context context, int resId) {
        final BitmapFactory.Options opt = new BitmapFactory.Options();
        opt.inPreferredConfig = Bitmap.Config.RGB_565;
        opt.inPurgeable = true;
        opt.inInputShareable = true;
        //获取资源图片
        InputStream is = context.getResources().openRawResource(resId);
        Bitmap bitmap = BitmapFactory.decodeStream(is, null, opt);
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new BitmapDrawable(context.getResources(), bitmap);
    }

   /* public static Drawable photoImage2Drawable(Context context, String path) {
        final BitmapFactory.Options opt = new BitmapFactory.Options();
        opt.inPreferredConfig = Bitmap.Config.RGB_565;
        opt.inPurgeable = true;
        opt.inInputShareable = true;
        Bitmap bitmap = null;
        try {
            //获取资源图片
            InputStream is = new FileInputStream(path);
            bitmap = BitmapFactory.decodeStream(is, null, opt);
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new BitmapDrawable(context.getResources(), bitmap);
    }*/

    /**
     * 根据路径获返回bitmap用于显示
     *
     * @param filePath
     * @return
     */
    public static Bitmap getBitmap(String filePath) {
        return BitmapFactory.decodeFile(filePath);
    }

    /**
     * 计算图片的缩放值
     *
     * @param options
     * @param reqWidth
     * @param reqHeight
     * @return
     */
    public static int calculateInSampleSize(BitmapFactory.Options options,
                                            int reqWidth, int reqHeight) {
        final int height = options.outHeight;
        final int width = options.outWidth;

        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {
            final int heightRatio = Math.round((float) height
                    / (float) reqHeight);
            final int widthRatio = Math.round((float) width / (float) reqWidth);
            inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
        }
        return inSampleSize;
    }

    /**
     * 从网络上获取图片资源
     *
     * @param path
     * @return
     */
    public static Bitmap getHttpBitmap(String path) {

        Bitmap bitmap = null;
        try {
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();

            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5000);
            if (conn.getResponseCode() == 200) {
                InputStream input = conn.getInputStream();
                bitmap = BitmapFactory.decodeStream(input);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    public static String byteToVoiceFile(byte[] b, String path) {
        BufferedOutputStream stream = null;
        File file = null;
        FileOutputStream fstream = null;
        try {
            file = new File(path);
            fstream = new FileOutputStream(file, false);
            stream = new BufferedOutputStream(fstream);
            stream.write(b);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (stream != null) {
                try {
                    stream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return file.getAbsolutePath();
    }


    public static void writeByteArrayToFile(File file, byte[] data) throws IOException {
        FileOutputStream out = null;
        try {
            out = openOutputStream(file, false);
            out.write(data);
            out.close();
        } finally {
            closeQuietly(out);
        }
    }

    public static void closeQuietly(OutputStream output) {
        closeQuietly((Closeable) output);
    }

    public static void closeQuietly(Closeable closeable) {
        try {
            if (closeable != null) {
                closeable.close();
            }
        } catch (IOException var2) {
        }

    }


    public static FileOutputStream openOutputStream(File file, boolean append) throws IOException {
        if (file.exists()) {
            if (file.isDirectory()) {
                throw new IOException("File \'" + file + "\' exists but is a directory");
            }
            if (!file.canWrite()) {
                throw new IOException("File \'" + file + "\' cannot be written to");
            }
        } else {
            File parent = file.getParentFile();
            if (parent != null && !parent.mkdirs() && !parent.isDirectory()) {
                throw new IOException("Directory \'" + parent + "\' could not be created");
            }
        }

        return new FileOutputStream(file, append);
    }

    /**
     * hasExist 检测文件是否已经存在
     *
     * @return Object 返回对象描述
     * @Exception 异常描述
     */
    public static boolean fileHasExist(String path) {
        try {
            File f = new File(path);
            if (!f.exists()) {
                return false;
            }
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    /**
     * 获取文件的相对路径文件名称(网络地址/本地文件 返回文件名)
     *
     * @param filename
     * @return
     */
    public static String getRelationFileName(String filename) {
        if (TextUtils.isEmpty(filename)) return null;
        filename = filename.substring(filename.lastIndexOf("/") + 1, filename.length());
        int voiceIndex = filename.lastIndexOf(".");//取消后缀名 隐藏文件
        if (-1 != voiceIndex) {
            filename = filename.substring(0, voiceIndex);
        }
        return filename;
    }
    public static boolean saveVedioFile(String path) {
        return false;
    }

    /**
     * 文件大小
     *
     * @return Object 返回对象描述
     * @Exception 异常描述
     */
    public static int getFileSize(String path) {
        try {
            File f = new File(path);
            if (!f.exists()) {
                return 0;
            }
            FileInputStream stream = new FileInputStream(f);
            return stream.available();
        } catch (Exception e) {
            return 0;
        }
    }

    /**
     * 文件大小
     *
     * @return Object 返回对象描述
     * @Exception 异常描述
     */
    public static long getFileSizes(String path) {
        try {
            File f = new File(path);
            if (!f.exists()) {
                return 0;
            }
            return f.length();
        } catch (Exception e) {
            return 0;
        }
    }

    /**
     * 获取文件的MB
     *
     * @param path
     * @return
     */
    public static double getFileSizeMB(String path) {
        DecimalFormat df = new DecimalFormat("#.00");
        return Double.valueOf(df.format((double) getFileSize(path) / 1048576));
    }

    /**
     * 获取文件大小
     *
     * @param size bytes
     * @return
     */
    public static String getFileSize(long size) {
        double kb = size / 1024;
        if (kb >= 100) {
            BigDecimal bd = new BigDecimal(kb / 1024);
            bd = bd.setScale(1, BigDecimal.ROUND_HALF_UP);
            return bd + "M";
        } else {
            return ((int) kb) + "K";
        }
    }

    /**
     * 删除文件
     */
    public static boolean deleteFile(String filePath) {
        boolean flag = false;
        File file = new File(filePath);
        // 路径为文件且不为空则进行删除
        if (file.isFile() && file.exists()) {
            file.delete();
            flag = true;
        }
        return flag;
    }

    /**
     * 删除文件与目录
     */
    public static boolean deleteFolder(String filePath) {
        boolean flag = false;
        File file = new File(filePath);
        // 判断目录或文件是否存在
        if (!file.exists()) { // 不存在返回 false
            return flag;
        } else {
            // 判断是否为文件
            if (file.isFile()) { // 为文件时调用删除文件方法
                return deleteFile(filePath);
            } else { // 为目录时调用删除目录方法
                return deleteDirectory(filePath);
            }
        }
    }

    /**
     * 删除目录
     *
     * @param filePath
     * @return
     */
    public static boolean deleteDirectory(String filePath) {
        boolean flag = false;
        // 如果sPath不以文件分隔符结尾，自动添加文件分隔符
        if (!filePath.endsWith(File.separator)) {
            filePath = filePath + File.separator;
        }
        File dirFile = new File(filePath);
        // 如果dir对应的文件不存在，或者不是一个目录，则退出
        if (!dirFile.exists() || !dirFile.isDirectory()) {
            return false;
        }
        flag = true;
        // 删除文件夹下的所有文件(包括子目录)
        File[] files = dirFile.listFiles();
        for (int i = 0; i < files.length; i++) {
            // 删除子文件
            if (files[i].isFile()) {
                flag = deleteFile(files[i].getAbsolutePath());
                if (!flag)
                    break;
            } // 删除子目录
            else {
                flag = deleteDirectory(files[i].getAbsolutePath());
                if (!flag)
                    break;
            }
        }
        if (!flag)
            return false;
        // 删除当前目录
        if (dirFile.delete()) {
            return true;
        } else {
            return false;
        }
    }


    /**
     * 获取视频缩略图（这里获取第一帧）
     *
     * @param filePath
     * @return
     */
    public Bitmap getVideoThumbnail(String filePath) {
        Bitmap bitmap = null;
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        try {
            retriever.setDataSource(filePath);
            bitmap = retriever.getFrameAtTime(TimeUnit.MILLISECONDS.toMicros(1));
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } finally {
            try {
                retriever.release();
            } catch (RuntimeException e) {
                e.printStackTrace();
            }
        }

        bitmapToString(bitmap, Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + "ffffff" + ".png");

        return bitmap;
    }

    /**
     * 是否有外存卡
     *
     * @return
     */
    public static boolean isExistExternalStore() {
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 外置存储卡的路径
     *
     * @return
     */
    public static String getExternalStorePath() {
        if (isExistExternalStore()) {
            return Environment.getExternalStorageDirectory().getAbsolutePath();
        }
        return null;
    }

    /**
     * save image from uri
     *
     * @param outPath
     * @param bitmap
     * @return
     */
    public static String saveBitmapToLocal(String outPath, Bitmap bitmap) {
        try {
            String imagePath = outPath + AESEncryptUtils.md5String(android.text.format.DateFormat.format("yyyy-MM-dd-HH-mm-ss",
                    System.currentTimeMillis()).toString()) + ".jpg";
            File file = new File(imagePath);
            if (!file.exists()) {
                file.createNewFile();
            }
            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(
                    new FileOutputStream(file));
            bitmap.compress(Bitmap.CompressFormat.PNG, 100,
                    bufferedOutputStream);
            bufferedOutputStream.close();
            LogManager.getLogger().s("photo image from data, path:" + imagePath);
            return imagePath;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 检查图片地址的合法
     *
     * @param mFilePath
     * @return
     */
    public static String checkPhotoPath(String mFilePath) {
        if (TextUtils.isEmpty(mFilePath)) {
            return null;
        }
        File file = new File(mFilePath);
        if (file == null || !file.exists()) {
            return null;
        }
        return mFilePath;
    }

    /**
     * 获取文件目录
     *
     * @return
     */
    public static File getFilePathName() {
        if (!isExistExternalStore()) {
            return null;
        }
        File directory = new File(MAR_DIR_VIDEO);
        if (!directory.exists() && !directory.mkdirs()) {
            LogManager.getLogger().s("Path to file could not be created");
            return null;
        }
        return directory;
    }

    /**
     * 新建文件的文件 文件名
     *
     * @return
     */
    public static String createCCPFileName() {
        Calendar c = Calendar.getInstance();
        c.setTimeInMillis(System.currentTimeMillis());

        int y = c.get(Calendar.YEAR);
        int m = c.get(Calendar.MONTH);
        int d = c.get(Calendar.DAY_OF_MONTH);
        int hour = c.get(Calendar.HOUR_OF_DAY);
        int minute = c.get(Calendar.MINUTE);
        int second = c.get(Calendar.SECOND);
        return y + "-" + m + "-" + d + "-" + hour + "-" + minute + "-" + second;
    }

    public static File TackVideoFilePath() {
         File localFile = new File(getFilePathName(), createCCPFileName() + ".mp4");
        //File localFile = new File(getFilePathName(), createCCPFileName());//取消后缀名 隐藏文件
        if ((!localFile.getParentFile().exists())
                && (!localFile.getParentFile().mkdirs())) {
            localFile = null;
        }
        return localFile;
    }

    @SuppressLint("NewApi")
    public static Bitmap createVideoThumbnail(String filePath) {
        Bitmap bitmap = null;
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        try {
            // retriever.setMode(MediaMetadataRetriever.);
            retriever.setDataSource(filePath);
            bitmap = retriever.getFrameAtTime(1000);
        } catch (Exception ex) {
        } finally {
            try {
                retriever.release();

            } catch (RuntimeException ex) {
            }
        }
        return bitmap;
    }


    /**
     * get suffix of file from path
     *
     * <pre>
     *      getFileExtension(null)               =   ""
     *      getFileExtension("")                 =   ""
     *      getFileExtension("   ")              =   "   "
     *      getFileExtension("a.mp3")            =   "mp3"
     *      getFileExtension("a.b.rmvb")         =   "rmvb"
     *      getFileExtension("abc")              =   ""
     *      getFileExtension("c:\\")              =   ""
     *      getFileExtension("c:\\a")             =   ""
     *      getFileExtension("c:\\a.b")           =   "b"
     *      getFileExtension("c:a.txt\\a")        =   ""
     *      getFileExtension("/home/admin")      =   ""
     *      getFileExtension("/home/admin/a.txt/b")  =   ""
     *      getFileExtension("/home/admin/a.txt/b.mp3")  =   "mp3"
     * </pre>
     *
     * @param filePath
     * @return
     */
    public static String getFileExtension(String filePath) {
        if (StringUtils.isBlank(filePath)) {
            return filePath;
        }

        int extenPosi = filePath.lastIndexOf(".");
        int filePosi = filePath.lastIndexOf(File.separator);
        if (extenPosi == -1) {
            return "";
        }
        return (filePosi >= extenPosi) ? "" : filePath.substring(extenPosi + 1);
    }
}

